import asyncio
import socket


async def scan_port(ip, port):
    try:
        # 创建一个异步的socket
        reader, writer = await asyncio.open_connection(ip, port)
        print(f"Port {port} on {ip} is open.")
        # 关闭连接
        writer.close()
    except ConnectionRefusedError:
        # 如果连接被拒绝，我们简单地打印一条消息或忽略它
        pass
    except Exception as e:
        print(f"Error connecting to {ip}:{port}: {e}")


async def main(ip, start_port, end_port):
    # 创建一个任务列表
    tasks = []
    for port in range(start_port, end_port + 1):
        task = asyncio.create_task(scan_port(ip, port))
        tasks.append(task)

        # 等待所有任务完成
    await asyncio.gather(*tasks)


# 使用脚本
if __name__ == "__main__":
    ip = "192.168.1.201"
    start_port = 5999
    end_port = 9554
    asyncio.run(main(ip, start_port, end_port))